package com.example.hosptial.newController;

import com.example.hosptial.model.enity.Department;
import com.example.hosptial.model.enity.Nurse;
import com.example.hosptial.repository.DepartmentRepository;
import com.example.hosptial.service.NurseService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class NurseManagementController {

    @Autowired
    private NurseService nurseService;

    @Autowired
    private DepartmentRepository departmentRepository;

    // 返回护士管理页面
    @GetMapping("/nurse-manage")
    public String getNurseManagePage(Model model) {
        List<Department> departments = departmentRepository.findAll();
        model.addAttribute("departments", departments);
        return "admin/nurse-manage";
    }

    // 获取所有护士信息
    @GetMapping("/nurses")
    @ResponseBody
    public ResponseEntity<List<Nurse>> getAllNurses() {
        List<Nurse> nurses = nurseService.getAllNurses();
        return ResponseEntity.ok(nurses);
    }

    // 根据部门ID获取护士信息
    @GetMapping("/nurses/department/{deptId}")
    @ResponseBody
    public ResponseEntity<List<Nurse>> getNursesByDepartment(@PathVariable("deptId") Integer deptId) {
        List<Nurse> nurses = nurseService.getNursesByDepartment(deptId);
        return ResponseEntity.ok(nurses);
    }

    @PostMapping("/addNurse")
    @ResponseBody
    public ResponseEntity<?> addNurse(@Valid @RequestBody Map<String, Object> request, BindingResult bindingResult) {
        try {
            // 验证输入
            if (bindingResult.hasErrors()) {
                Map<String, String> errors = new HashMap<>();
                for (FieldError error : bindingResult.getFieldErrors()) {
                    errors.put(error.getField(), error.getDefaultMessage());
                }
                return ResponseEntity.badRequest().body(errors);
            }

            // 创建护士对象
            Nurse nurse = new Nurse();
            nurse.setNurseId(request.get("nurseId").toString());
            nurse.setNurseName(request.get("nurseName").toString());
            nurse.setNurseGender(request.get("nurseGender").toString());
            nurse.setNurseAge(Integer.parseInt(request.get("nurseAge").toString()));
            nurse.setNurseIdCard(request.get("nurseIdCard").toString());
            nurse.setNursePhone(request.get("nursePhone").toString());

            // 设置科室
            Integer deptId = Integer.parseInt(request.get("deptId").toString());
            Department department = departmentRepository.findById(deptId)
                    .orElseThrow(() -> new RuntimeException("科室不存在"));
            nurse.setDepartment(department);

            // 保存护士信息
            Nurse savedNurse = nurseService.addNurse(nurse);

            // 返回成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("nurseId", savedNurse.getNurseId());
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/nurses/assignments/{nurseId}")
    @ResponseBody
    public ResponseEntity<?> getNurseWardAssignments(@PathVariable("nurseId") String nurseId) {
        try {
            List<Map<String, Object>> assignments = nurseService.getNurseWardAssignments(nurseId);
            return ResponseEntity.ok(assignments);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @PostMapping("/nurses/assignments/cancel")
    @ResponseBody
    public ResponseEntity<?> cancelNurseWardAssignment(
            @RequestParam("nurseId") String nurseId,
            @RequestParam("wardId") Integer wardId) {
        try {
            nurseService.cancelNurseWardAssignment(nurseId, wardId);
            return ResponseEntity.ok(Map.of("success", true));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/nurses/{nurseId}/department/floors")
    @ResponseBody
    public ResponseEntity<?> getDepartmentFloors(@PathVariable("nurseId") String nurseId) {
        try {
            Nurse nurse = nurseService.getAllNurses().stream()
                .filter(n -> n.getNurseId().equals(nurseId))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("护士不存在"));
            
            List<Integer> floors = nurseService.getFloorsByDepartment(nurse.getDepartment().getDeptId());
            return ResponseEntity.ok(floors);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/nurses/{nurseId}/department/floors/{floorNum}/wards")
    @ResponseBody
    public ResponseEntity<?> getFloorWards(
            @PathVariable("nurseId") String nurseId,
            @PathVariable("floorNum") Integer floorNum) {
        try {
            Nurse nurse = nurseService.getAllNurses().stream()
                .filter(n -> n.getNurseId().equals(nurseId))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("护士不存在"));
            
            List<Map<String, Object>> wards = nurseService.getWardsByFloor(
                nurse.getDepartment().getDeptId(), floorNum);
            return ResponseEntity.ok(wards);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @PostMapping("/nurses/assignments/assign")
    @ResponseBody
    public ResponseEntity<?> assignWardToNurse(
            @RequestParam("nurseId") String nurseId,
            @RequestParam("wardId") Integer wardId) {
        try {
            nurseService.assignWardToNurse(nurseId, wardId);
            return ResponseEntity.ok(Map.of("success", true));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
} 